package leo.util
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	/**
	 * 图片播放器 
	 * @author leo
	 * 
	 */	
	public class Animation extends Bitmap
	{
		/**
		 * BitmapData列表 
		 */		
		private var bmdList :Vector.<BitmapData>
		/**
		 * 时间器 
		 */		
		private var timer :Timer;
		/**
		 * 当前帧，外部只能get 
		 */		
		private var _curFrame :int;
		/**
		 * 停止在某一帧 
		 */		
		private var _stopFrame :int;
		/**
		 * 图片播放器 
		 * @param bmdList BitmapData列表 
		 * 
		 */		
		public function Animation(bmdList :Vector.<BitmapData>)
		{
			this.bmdList = bmdList;
			
			this._curFrame = 0;
			this.stopFrame = 0;
			
			this.timer = new Timer(100);
			this.timer.addEventListener(TimerEvent.TIMER,timerHandler);
		}
		/**
		 * 
		 * 开始播放
		 */		
		public function play():void
		{
			if(this.timer)
			{
				this.timer.reset();
				this.timer.start();
			}
		}
		/**
		 * 停止播放 
		 * 
		 */		
		public function stop():void
		{
			if(this.timer)
			{
				this.timer.stop();
			}
		}
		/**
		 * 设置帧频，其实是timer的延迟时间，单位为毫秒 
		 * @param value
		 * 
		 */		
		public function set frameRate(value :int):void
		{
			if(this.timer)
			{
				this.timer.delay = value;
			}
		}
		/**
		 * 循环次数 
		 * @param value
		 * 
		 */		
		public function set loop(value :int):void
		{
			this.timer.repeatCount = value * this.bmdList.length;
		}

		public function get curFrame():int
		{
			return _curFrame;
		}
		
		public function get stopFrame():int
		{
			return _stopFrame;
		}
		
		public function set stopFrame(value:int):void
		{
			_stopFrame = value;
			_curFrame = stopFrame;
			this.bitmapData = this.bmdList[stopFrame];
			this.stop();
		}

		private function timerHandler(event :TimerEvent):void
		{
			_curFrame++;
			if(_curFrame >= this.bmdList.length)
			{
				_curFrame = stopFrame;
				this.bitmapData = this.bmdList[stopFrame];
				return;
			}
			this.bitmapData = this.bmdList[_curFrame];
		}
	}
}